<template>
  <div class="flex-1">
    <div>
      <el-row>
        <el-input
          size="mini"
          v-model="search.projectname"
          placeholder="请输入项目名称"
          style="width: 200px"
        ></el-input>
        <el-button
          size="mini"
          type="primary"
          @click="fetch()"
        >搜索</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="formVisible=true"
        >新增项目</el-button>
      </el-row>
      <el-table
        :data="projects"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column
          type="selection"
          width="50"
        >
        </el-table-column>
        <el-table-column
          type="index"
          width="50"
        >
        </el-table-column>
        <el-table-column
          prop="projectname"
          label="项目名称"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="负责人"
          width="180"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="editProject(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              @click="deleteUser(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="search.currentpage"
        :page-size.sync="search.pagesize"
        layout="prev, pager, next, ->, total"
        :total="search.total"
        @size-change="fetch"
        @current-change="fetch"
        @prev-click="fetch"
        @next-click="fetch"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="编辑项目"
      :visible.sync="formVisible"
      @close="cancelForm"
    >
      <el-form
        :model="form"
        :rules="rules"
        label-position="top"
        ref="form"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form-item
          label="项目名称"
          prop="projectname"
        >
          <el-input v-model="form.projectname"></el-input>
        </el-form-item>
        <el-form-item
          label="负责人"
          prop="owner"
        >
          <el-select
            v-model="form.owner"
            filterable
            remote
            reserve-keyword
            placeholder="请输入用户名"
            :remote-method="searchUsers"
            :loading="selLoading"
          >
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click.native="formVisible=false">取 消</el-button>
        <el-button
          type="primary"
          @click.native="saveForm"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { projectList, newProject, editProject, deleteProject } from '@/api/project'
import { user as userRes } from '@/resources'
import { errorMessage } from '@/utils/helpers'
import {userList, getUserName} from '@/api/user'
export default {
  data () {
    return {
      loading: false,
      selLoading: false,
      search: {
        projectname: '',
        pagesize: 10,
        currentpage: 0,
        total: 0
      },
      form: {
        projectname: '',
        owner: ''
      },
      rules: {
        projectname: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          }
        ],
        owner: [
          {
            required: true,
            message: '请输入负责人',
            trigger: 'blur'
          }
        ]
      },
      formVisible: false,
      projects: [],
      users: []
    }
  },
  methods: {
    fetch () {
      this.loading = true
      projectList(this.search)
        .then(response => {
          const data = response.data
          this.projects = data.list
          this.search.total = data.total
          this.loading = false
        })
        .catch(err => {
          this.loading = false
          this.$message({
            type: 'error',
            message: errorMessage(err, '刷新失败')
          })
        })
    },
    cancelForm () {
      this.$refs.form.resetFields()
      this.formVisible = false
    },
    editProject (project) {
      this.form.id = project.id
      this.form.projectname = project.projectname
      // 根据user的id获取对应的username
      getUserName(project.owner).then(response => {
        const data = response.data
        this.form.owner = project.owner
        this.users.push({id: project.owner, username: data.username})
        this.formVisible = true
      }).catch(err => {
        this.$message({
          type: 'error',
          message: errorMessage(err, '获取用户名失败')
        })
        this.formVisible = true
      })
    },
    saveForm () {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            editProject(this.form.id, this.form).then(() => {
              this.cancelForm()
              this.$message({
                type: 'success',
                message: '修改成功'
              })
              this.fetch()
            })
              .catch(err => {
                this.$message({
                  type: 'error',
                  message: errorMessage(err, '修改失败')
                })
              })
          } else {
            newProject(this.form)
              .then(() => {
                this.cancelForm()
                this.$message({
                  type: 'success',
                  message: '新增成功'
                })
                this.fetch()
              })
              .catch(err => {
                this.$message({
                  type: 'error',
                  message: errorMessage(err, '新增失败')
                })
              })
          }
        }
      })
    },
    searchUsers (username) {
      if (username !== '') {
        this.selLoading = true
        userList({username}).then(response => {
          const data = response.data
          this.users = data.list
          this.selLoading = false
        }).catch(err => {
          this.$message({
            type: 'error',
            message: errorMessage(err, '搜索失败')
          })
        })
      } else {
        this.users = []
        this.selLoading = false
      }
    },
    deleteUser (user) {
      this.$confirm(
        `This action will remove the selected user: ${
          user.username
        } forever, still going on?`,
        '提示',
        {
          type: 'warning'
        }
      )
        .then(() => {
          userRes.delete({ _id: user._id }).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.fetch()
          })
        })
        .catch(() => {})
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.fetch()
    })
  }
}
</script>

<style lang="stylus" scoped>
.el-row {
  margin-left: 1px;
  margin-bottom: 1px;

  .el-button {
    margin-left: 0;
  }
}

.el-pagination {
  padding: 0 1px;
  background-color: #fff;
  border: solid #eaeef5 1px;
  border-top: none;
}
</style>
